package com.g2.admin.controller;

import com.g2.admin.common.constant.Constants;
import com.g2.admin.common.constant.RedisConstants;
import com.g2.admin.utils.Base64Util;
import com.g2.admin.utils.RedisUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码操作处理
 */
@RestController
@RequestMapping("captcha")
@Slf4j
public class CaptchaController extends BaseController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    @Autowired
    private RedisUtil<String> redisUtil;

    // 验证码类型
    @Value("${g2.captcha.type}")
    private String captchaType;

    /**
     * 生成验证码，前端需要在生成的base64字符串前加：data:image/jpg;base64,
     */
    @GetMapping()
    public String getCaptcha() {
        String capStr = null, code = null;
        BufferedImage image = null;
        // 生成验证码
        if (Constants.CAPTCHA_MATH.equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if (Constants.CAPTCHA_CHAR.equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        // 采用sessionID作为唯一标识
        redisUtil.set(RedisConstants.getKeyCaptcha(getSessionId()), code, RedisConstants.TIME_MIN_FIVE);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            log.error("生成验证码图片异常", e);
        }

        return Base64Util.encode(os.toByteArray());
    }

    /**
     * 验证验证码
     */
    @GetMapping("/verify")
    public boolean verifyCaptcha(String code) {
        boolean rs = code.equals(redisUtil.get(RedisConstants.getKeyCaptcha(getSessionId())));
        // 验证后则删除验证码
        redisUtil.delete(RedisConstants.getKeyCaptcha(getSessionId()));
        return rs;
    }

}
